#include "shotscreenswebapi.h"
#include <QNetworkCookieJar>
#include <QList>
#include <QFile>
#include <QNetworkProxy>
#include <QHttp>
#include <QByteArray>
#include <QtGui/QImage>
#include <QNetworkProxy>
#include <QBuffer>
#include <QStringList>
ShotScreensWebAPI::ShotScreensWebAPI(QObject *parent, QString login, QString password) :
    QObject(parent)
{
    is_login = false;
    network_manager = new QNetworkAccessManager();
    req = QNetworkRequest();
    sec_info.session_id = "";
    sec_info.user_name = login;
    sec_info.user_password = password;
    login_url = QUrl("http://shotscreens.appspot.com/account/login/");
    logout_url = QUrl("http://shotscreens.appspot.com/account/logout/");
    create_folder_url=QUrl("http://shotscreens.appspot.com/gallery/create_album/");
    upload_url=QUrl("http://shotscreens.appspot.com/gallery/upload_picture/");
    folder_list_url=QUrl("http://shotscreens.appspot.com/gallery/list_album/");

    CurState=NO_STATE;

    ConnectAll();


}

void ShotScreensWebAPI::ConnectAll()
{
    connect(network_manager, SIGNAL(finished(QNetworkReply*)), SLOT(RequestIsFinished(QNetworkReply*)));

}

void ShotScreensWebAPI::Login()
{
    network_manager = new QNetworkAccessManager();
    ConnectAll();

    if(is_login)
    {
        Logout();
    }
    CurState = LOGIN_STATE;
    req_params.clear();
    req_params.append("username=");
    req_params = req_params.append(sec_info.user_name);
    req_params = req_params.append("&password=");
    req_params = req_params.append(sec_info.user_password);

    req = QNetworkRequest(login_url);
    network_manager -> post(req, req_params.toUtf8());
}

void ShotScreensWebAPI::Logout()
{
    if(!is_login) return;
    is_login=false;

    network_manager = new QNetworkAccessManager();

    ConnectAll();
    CurState = LOGOUT;
    req_params.clear();
    req = QNetworkRequest(logout_url);

    network_manager->post(req, req_params.toUtf8());
}
void ShotScreensWebAPI::CreateFolder(QString folder_name)
{

    if(!is_login)
    {
        emit OnError(CurState);
        return;
    }

    CurState = CREATE_FOLDER_STATE;
    req_params.clear();
    req_params = req_params.append("name=");

    req_params = req_params.append(folder_name);

    req = QNetworkRequest(create_folder_url);
    req.setHeader(QNetworkRequest::SetCookieHeader,sec_info.session_id);
    network_manager ->post(req,req_params.toUtf8());


}

void ShotScreensWebAPI::GetFolderList()
{
    if(!is_login)
    {
        return;
    }

    CurState = GET_FOLDER_LIST;
    network_manager = new QNetworkAccessManager();
    ConnectAll();
    req = QNetworkRequest(folder_list_url);
    QString cookie;

    post_array.clear();

    cookie = cookie.append("sessionid=");

    cookie = cookie.append((sec_info.session_id.toAscii().data()));

    req.setRawHeader("Cookie", cookie.toAscii().data());

    network_manager -> get(req);




}

void ShotScreensWebAPI::UploadImage(QString image_caption, QString folder_hash, QByteArray image_data)
{

    if(!is_login)
    {
        emit OnError(CurState);
        return;
    }

    CurState = UPLOAD_FILE;
    network_manager = new QNetworkAccessManager();
    ConnectAll();

    req = QNetworkRequest(upload_url);
    req.setUrl(upload_url);

    QString cookie;
    cookie = cookie.append("sessionid=");
    cookie = cookie.append(sec_info.session_id.toAscii().data());
    req_params.clear();
    req.setRawHeader("Cookie", cookie.toAscii().data());

    req.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data; boundary=7db288ed04bc");
    post_array.clear();

    post_array = post_array.append("--7db288ed04bc\r\n");
    post_array = post_array.append("Content-Disposition: form-data; name=\"album\"\r\n\r\n");
    post_array = post_array.append(folder_hash);
    post_array = post_array.append("\r\n");


    post_array = post_array.append("--7db288ed04bc\r\n");
    post_array = post_array.append("Content-Disposition: form-data; name=\"caption\"\r\n\r\n");
    post_array = post_array.append(image_caption.toAscii().data());
    post_array = post_array.append("\r\n");

    post_array = post_array.append("--7db288ed04bc\r\n");
    post_array = post_array.append("Content-Disposition: form-data; name=\"data\"; filename=\"");
    post_array = post_array.append(image_caption.toAscii().data());
    post_array = post_array.append("\"\r\n");
    post_array = post_array.append("Content-Type: image/x-png\r\n\r\n");
    post_array = post_array.append(image_data);
    post_array = post_array.append("\r\n");
    post_array = post_array.append("--7db288ed04bc--\r\n");


    network_manager -> post(req, post_array);


}

//****
int ShotScreensWebAPI::GetCurrentAPIState()
{

        switch(CurState)
        {
        case NO_STATE: return NO;

        case LOGIN_STATE: return LOGIN;

        case GET_FOLDER_LIST: return GET_FOLDER_LIST_STATE;

        case CREATE_FOLDER_STATE: return CREATE_FOLDER;

        case UPLOAD_FILE: return UPLOAD_FILE_STATE;

        default:
            return -1;
        }
}

void ShotScreensWebAPI::RequestIsFinished(QNetworkReply *reply)
{
    int bytes_received = reply->bytesAvailable();
    Q_UNUSED(bytes_received);
    QByteArray data = reply->readAll();
    QBuffer temp_buffer;
    temp_buffer.open(QIODevice::ReadWrite);

    if(reply -> error())
    {
         qDebug("Error! text %s",reply ->errorString().toAscii().data());
         return;
    }

    QNetworkCookieJar *cookiesJAR = network_manager->cookieJar();

    temp_buffer.write(data);


    int i=0;

    switch (CurState)
    {
    case LOGIN_STATE:
        if(cookiesJAR -> cookiesForUrl(login_url).count() > 0)
        {
            sec_info.session_id = QString(cookiesJAR -> cookiesForUrl(login_url).at(0).value());
            is_login=true;
            emit OnFinish(true);
        }
        else
        {
            emit OnFinish(false);
        }

        break;

    case CREATE_FOLDER_STATE:
        emit OnFinish(true);
        break;

    case GET_FOLDER_LIST:
        folderNames.clear();
        folderHashes.clear();

        temp_buffer.seek(0);
        while(temp_buffer.canReadLine())
        {

           QByteArray str = temp_buffer.readLine();
           if(str.length()>2)
            {
                QString string(str);
                int pos = str.indexOf(";");
                folderNames.append(string.mid(0, pos));
                folderHashes.append(string.mid(pos + 1));
                i++;
            }
        }



        emit OnFinish(true);
        break;
    case UPLOAD_FILE:
        emit OnFinish(true);
        break;
    case LOGOUT:
         emit OnFinish(true);
         break;
    default:
         break;
    }

    temp_buffer.close();
    reply -> deleteLater();



}
